#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sched.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>

//nc -u -l 172.27.1.12 60000
//nc -u 172.27.1.12 50000
int main(int argc, const char *argv[])
{
    int tcp_socket, con_socket, ret_recv;
    struct sockaddr_in peeraddr;
    //char buf[128] = {0};
    char buf[12];
    int len;
    tcp_socket = socket(AF_INET, SOCK_STREAM, 0);
    if(tcp_socket < 0) {
        perror("fail to socket");
        exit(1);
    }

    char *addr = "192.168.5.114";
    peeraddr.sin_family = AF_INET;
    peeraddr.sin_port = htons(50000);
    //peeraddr.sin_addr.s_addr = inet_addr("172.27.1.12");
    //peeraddr.sin_addr.s_addr = inet_addr("192.168.1.101");
    peeraddr.sin_addr.s_addr = inet_addr(addr);

    if(connect(tcp_socket, (struct sockaddr*)&peeraddr, sizeof(peeraddr)) == -1) {
        perror("fail to connect");
        exit(1);
    }

    //bzero(buf, sizeof(buf));
    //fgets(buf, sizeof(buf), stdin);
    //if(strncmp(buf, "quit", 4) == 0) {
    //    break;
    //}
 
    int testTotal = 10;

    //创建子进程
    pid_t pid1 = fork();
    printf("pid1--%d\n", pid1);
    if(pid1 == -1) {                //创建子进程, 失败
        perror("fork 1\n");
        exit(1);
    } else if(pid1 == 0) {          //子进程
        int j = 0;
        while(1) {
            testTotal = j;
            printf("------child---%d---tcp_socket[%d--%p]--testTotal[%d-%p]\n", j++, tcp_socket, &tcp_socket, testTotal, &testTotal);
            char buf[12] = "child----\n";
            send(tcp_socket, buf, sizeof(buf), 0);
            sleep(2);
        }
    } else {                        //父进程
        int t = 0;
        while(1) {
            testTotal = t;
            printf("parent--%d---tcp_socket[%d--%p]--testTotal[%d-%p]\n", t++, tcp_socket, &tcp_socket, testTotal, &testTotal);
            char buf[12] = "parent---\n";
            send(tcp_socket, buf, sizeof(buf), 0);
            sleep(1);
            if (t > 5) { 
                int c = close(tcp_socket); 
                break;
                printf("close---------%d\n", c);
            }
        }

        //waitpid(pid1, NULL, 0);
        printf("父进程\n");
        //while(1);
    }

    close(tcp_socket);

    return 0;
}

